<template>
  <div class="library-view">
    <!-- 搜索状态提示 -->
    <div v-if="isSearching" class="search-status">
      <el-alert
          :closable="false"
          :title="searchAlertTitle"
          class="search-alert"
          show-icon
          type="info"
      >
        <template #append>
          <el-button type="text" @click="clearSearch">清除搜索</el-button>
        </template>
      </el-alert>
    </div>

    <!-- 歌曲表格 -->
    <el-table
        v-loading="loading"
        :data="songs"
        :row-key="(row) => row.songId"
        border
        empty-text="暂无歌曲数据"
        style="width: 100%"
        class="song-table"
        @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" />

      <!-- 曲名列（带封面） -->
      <el-table-column label="曲名" width="300">
        <template #default="scope">
          <div class="song-info">
            <div class="song-cover-container">
              <img
                  :alt="scope.row.songName"
                  :src="scope.row.coverUrl || defaultCover"
                  class="song-cover"
                  @error="handleImageError"
              />
              <div class="play-overlay" @click.stop="playSong(scope.row, scope.$index)">
                <el-icon class="play-icon">
                  <VideoPlay/>
                </el-icon>
              </div>
              <!-- 播放指示器 -->
              <div v-if="isCurrentPlayingSong(scope.row)" class="playing-indicator">
                <div class="equalizer">
                  <span class="bar"></span>
                  <span class="bar"></span>
                  <span class="bar"></span>
                  <span class="bar"></span>
                </div>
              </div>
            </div>
            <div class="song-details">
              <div class="song-name-container">
                <span :class="{ 'playing': isCurrentPlayingSong(scope.row) }" class="song-name">
                  {{ scope.row.songName }}
                </span>
                <el-icon v-if="isCurrentPlayingSong(scope.row)" class="volume-icon">
                  <Microphone/>
                </el-icon>
              </div>
              <div class="song-artist">{{ scope.row.artistName }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="歌手" prop="artistName" width="150"/>
      <el-table-column label="专辑" prop="album" width="200"/>

      <!-- 喜欢列 -->
      <el-table-column label="喜欢" width="80">
        <template #default="scope">
          <el-button
              @click.stop="likeSong(scope.row)"
              :type="scope.row.likeStatus === 1 ? 'danger' : 'default'"
              :loading="scope.row.likeLoading"
              circle
              class="like-btn"
          >
            <el-icon>
              <Star/>
            </el-icon>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="时长" prop="duration" width="100">
        <template #default="scope">
          <span :class="{ 'playing-duration': isCurrentPlayingSong(scope.row) }">
            {{ formatDuration(scope.row.duration) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="发行时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.releaseTime) }}
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button
              :class="{ 'playing-btn': isCurrentPlayingSong(scope.row) }"
              size="small"
              type="primary"
              @click.stop="playSong(scope.row, scope.$index)"
          >
            <el-icon>
              <VideoPlay/>
            </el-icon>
            {{ isCurrentPlayingSong(scope.row) ? '播放中' : '播放' }}
          </el-button>
          <el-button
              :loading="scope.row.downloadLoading"
              size="small"
              type="success"
              @click.stop="downloadSong(scope.row)"
          >
            <el-icon>
              <Download/>
            </el-icon>
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, onUnmounted, ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {Download, Microphone, Star, VideoPlay} from '@element-plus/icons-vue'
import {isLogin} from '../utils/auth'
import http from "@/request/http.js"
import {usePlayer} from '@/utils/player.js'

const route = useRoute()
const router = useRouter()
const {playerState, playSong: playSongInPlayer, setPlaylist} = usePlayer()

// 响应式数据
const loading = ref(false)
const songs = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索相关状态
const isSearching = ref(false)
const currentSearchQuery = ref('')

// 使用 Base64 内联图片作为默认封面（不会触发网络请求）
const defaultCover = ''

// 计算属性：搜索提示标题
const searchAlertTitle = computed(() => {
  return `搜索 "${currentSearchQuery.value}" 的结果，共 ${total.value} 条`
})

// 检查是否是当前正在播放的歌曲
const isCurrentPlayingSong = (song) => {
  if (!playerState.currentSong || !song) return false

  const currentSongId = playerState.currentSong.songId || playerState.currentSong.id
  const songId = song.songId || song.id

  return currentSongId === songId && playerState.isPlaying
}

// 使用模拟数据
const useMockData = () => {
  console.log('使用模拟数据')

  // 如果有搜索词，过滤模拟数据
  let mockSongs = [
    {
      songId: 2,
      songName: "Fool's Gold",
      artistName: 'Aaron Carter',
      album: 'LøVë',
      duration: '196.98',
      likeStatus: 0, // 未登录状态下全部设为0
      releaseTime: '2017-02-10',
      coverUrl: defaultCover,
      audioUrl: 'http://example.com/song1.mp3'
    },
    {
      songId: 3,
      songName: 'Sooner Or Later',
      artistName: 'Aaron Carter',
      album: 'LøVë',
      duration: '212.82',
      likeStatus: 0, // 未登录状态下全部设为0
      releaseTime: '2017-02-10',
      coverUrl: defaultCover,
      audioUrl: 'http://example.com/song2.mp3'
    },
    {
      songId: 4,
      songName: 'Lost Stars',
      artistName: 'Maroon 5',
      album: 'V',
      duration: '266.77',
      likeStatus: 0, // 未登录状态下全部设为0
      releaseTime: '2014-09-02',
      coverUrl: defaultCover,
      audioUrl: 'http://example.com/song3.mp3'
    },
    {
      songId: 5,
      songName: '晴天的周末在去学校补课的路上遇见了喜欢的人',
      artistName: 'AniFace',
      album: '致青春的你',
      duration: '211.35',
      likeStatus: 0, // 未登录状态下全部设为0
      releaseTime: '2017-05-08',
      coverUrl: defaultCover,
      audioUrl: 'http://example.com/song4.mp3'
    },
    {
      songId: 7,
      songName: '7 rings',
      artistName: 'Ariana Grande',
      album: '7 rings',
      duration: '178.71',
      likeStatus: 0, // 未登录状态下全部设为0
      releaseTime: '2019-02-08',
      coverUrl: defaultCover,
      audioUrl: 'http://example.com/song5.mp3'
    }
  ]

  // 如果有搜索词，过滤数据
  if (isSearching.value && currentSearchQuery.value) {
    const query = currentSearchQuery.value.toLowerCase()
    mockSongs = mockSongs.filter(song =>
        song.songName.toLowerCase().includes(query) ||
        song.artistName.toLowerCase().includes(query) ||
        song.album.toLowerCase().includes(query)
    )
  }

  // 添加加载状态字段
  const songsWithLoading = mockSongs.map(song => ({
    ...song,
    likeLoading: false,
    downloadLoading: false
  }))

  songs.value = songsWithLoading
  total.value = isSearching.value ? mockSongs.length : 498

  if (isSearching.value) {
    ElMessage.info(`搜索"${currentSearchQuery.value}"，使用模拟数据展示 ${mockSongs.length} 条结果`)
  } else {
    ElMessage.info('使用模拟数据展示')
  }
}

// 获取歌曲列表
const fetchSongs = async () => {
  loading.value = true
  try {
    console.log('📤 发送请求...')

    // 构建请求参数
    const requestData = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 如果有搜索词，添加到请求参数中
    if (isSearching.value && currentSearchQuery.value) {
      requestData.songName = currentSearchQuery.value
      requestData.artistName = currentSearchQuery.value
      requestData.album = currentSearchQuery.value
    }

    console.log('请求参数:', JSON.stringify(requestData, null, 2))

    // 发送 POST 请求
    const response = await http.post("/song/getAllSongs", requestData)
    console.log('收到响应:', response)

    if (response.code === 0) {
      if (response.data && response.data.items) {
        // 处理歌曲数据：如果用户未登录，重置所有喜欢状态为0
        const processedSongs = response.data.items.map(song => {
          // 如果用户未登录，强制设置likeStatus为0
          const likeStatus = isLogin() ? (song.likeStatus || 0) : 0

          return {
            ...song,
            likeStatus: likeStatus,
            likeLoading: false,
            downloadLoading: false
          }
        })

        songs.value = processedSongs
        total.value = response.data.total
        console.log('✅ 成功解析歌曲数据，数量:', songs.value.length)

        if (isSearching.value) {
          ElMessage.success(`找到 ${songs.value.length} 首与"${currentSearchQuery.value}"相关的歌曲`)
        } else {
          ElMessage.success(`成功加载 ${songs.value.length} 首歌曲`)
        }
      } else {
        songs.value = []
        total.value = 0
        console.warn('❓ 响应数据中未找到items字段:', response.data)

        if (isSearching.value) {
          ElMessage.warning(`未找到与"${currentSearchQuery.value}"相关的歌曲`)
        } else {
          ElMessage.warning('暂无歌曲数据')
        }
      }
    } else {
      console.error('获取歌曲失败:', response.message)
      songs.value = []
      total.value = 0
      ElMessage.error(response.message || '获取歌曲失败')
    }
  } catch (error) {
    console.error('❌ 请求失败:', error)

    if (error.response) {
      console.error('错误响应:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })

      if (error.response.status === 400) {
        ElMessage.error('请求参数错误，请检查参数格式')
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误')
      }
    }

    songs.value = []
    total.value = 0

    // 使用模拟数据作为备选
    useMockData()
  } finally {
    loading.value = false
  }
}

// 监听登录状态变化
const handleLoginStatusChange = () => {
  console.log('登录状态变化，重新加载歌曲数据')
  // 重新获取歌曲数据，确保喜欢状态正确
  fetchSongs()
}

// 监听播放状态变化
const handlePlayStateChange = () => {
  // 当播放状态改变时，强制更新表格以刷新样式
  // 这里我们使用一个简单的技巧：重新赋值songs数组来触发响应式更新
  songs.value = [...songs.value]
}

// 监听路由变化，处理搜索参数
watch(
    () => route.query.search,
    (newSearchQuery) => {
      if (newSearchQuery) {
        currentSearchQuery.value = newSearchQuery
        isSearching.value = true
        currentPage.value = 1
        fetchSongs()
      } else {
        currentSearchQuery.value = ''
        isSearching.value = false
        currentPage.value = 1
        fetchSongs()
      }
    },
    {immediate: true}
)

// 组件挂载时自动获取歌曲
onMounted(() => {
  if (route.query.search) {
    currentSearchQuery.value = route.query.search
    isSearching.value = true
  }

  // 监听登录状态变化
  window.addEventListener('loginStatusChanged', handleLoginStatusChange)

  // 监听播放状态变化
  window.addEventListener('playStateChanged', handlePlayStateChange)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('loginStatusChanged', handleLoginStatusChange)
  window.removeEventListener('playStateChanged', handlePlayStateChange)
})

// 清除搜索
const clearSearch = () => {
  router.push({path: '/library'})
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchSongs()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchSongs()
}

// 行点击事件
const handleRowClick = (row) => {
  const index = songs.value.findIndex(song => song.songId === row.songId)
  if (index !== -1) {
    playSong(row, index)
  }
}

// 播放歌曲 - 修改为传递当前索引和设置播放列表
const playSong = (song, index) => {
  console.log('播放歌曲', song, '索引:', index, '播放列表数量:', songs.value.length)

  // 设置当前页面的歌曲列表为播放列表
  setPlaylist(songs.value, index)

  // 播放指定歌曲
  playSongInPlayer(song, songs.value, index)
  ElMessage.success(`开始播放: ${song.songName} - ${song.artistName}`)

  // 触发播放状态变化事件
  window.dispatchEvent(new CustomEvent('playStateChanged'))
}

// 下载歌曲
const downloadSong = async (song) => {
  if (!song.audioUrl) {
    ElMessage.error('该歌曲暂无下载地址')
    return
  }

  song.downloadLoading = true

  try {
    console.log('开始下载歌曲:', song.songName)

    // 创建下载链接
    const link = document.createElement('a')
    link.href = song.audioUrl

    // 设置下载文件名
    const fileName = `${song.songName} - ${song.artistName}.mp3`.replace(/[<>:"/\\|?*]/g, '_')
    link.download = fileName

    // 添加到DOM并触发点击
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success(`开始下载: ${song.songName}`)

    // 模拟下载进度
    setTimeout(() => {
      ElMessage.success(`歌曲 "${song.songName}" 下载完成，已保存到下载文件夹`)
    }, 1000)

  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`下载失败: ${error.message}`)
  } finally {
    song.downloadLoading = false
  }
}

// 图片加载失败处理
const handleImageError = (event) => {
  event.target.src = defaultCover
}

// 收藏歌曲
const collectSong = async (songId) => {
  try {
    const response = await http.post(`/favorite/collectSong?songId=${songId}`)
    return response
  } catch (error) {
    console.error('收藏歌曲失败:', error)
    throw error
  }
}

// 取消收藏歌曲
const cancelCollectSong = async (songId) => {
  try {
    const response = await http.delete(`/favorite/cancelCollectSong?songId=${songId}`)
    return response
  } catch (error) {
    console.error('取消收藏歌曲失败:', error)
    throw error
  }
}

// 喜欢/取消喜欢歌曲
const likeSong = async (song) => {
  if (!isLogin()) {
    ElMessage.warning('请先登录后再进行喜欢操作')
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }

  song.likeLoading = true

  try {
    if (song.likeStatus === 1) {
      const response = await cancelCollectSong(song.songId)
      if (response.code === 0) {
        song.likeStatus = 0
        ElMessage.success(`已取消喜欢: ${song.songName}`)

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'remove',
            songId: song.songId,
            song: song
          }
        }))
      } else {
        ElMessage.error(response.message || '取消喜欢失败')
      }
    } else {
      const response = await collectSong(song.songId)
      if (response.code === 0) {
        song.likeStatus = 1
        ElMessage.success(`已添加到喜欢: ${song.songName}`)

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'add',
            songId: song.songId,
            song: {
              id: song.songId,
              name: song.songName,
              artistName: song.artistName,
              album: song.album,
              duration: song.duration,
              likeStatus: 1,
              releaseTime: song.releaseTime,
              coverUrl: song.coverUrl,
              audioUrl: song.audioUrl
            }
          }
        }))
      } else {
        ElMessage.error(response.message || '添加喜欢失败')
      }
    }
  } catch (error) {
    console.error('喜欢操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    song.likeLoading = false
  }
}

// 格式化时长（秒转换为分:秒）
const formatDuration = (duration) => {
  if (!duration) return '0:00'

  try {
    const seconds = typeof duration === 'string' ? parseFloat(duration) : duration

    if (isNaN(seconds)) return '0:00'

    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  } catch {
    return '0:00'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  try {
    return new Date(dateString).toLocaleDateString('zh-CN')
  } catch {
    return '未知'
  }
}
</script>

<style scoped>
.library-view {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  padding-bottom: 80px;
}

.search-status {
  margin-bottom: 20px;
}

.search-alert {
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.song-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.song-cover-container {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  cursor: pointer;
}

.song-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
  cursor: pointer;
}

.play-overlay:hover {
  opacity: 1;
}

.play-icon {
  color: white;
  font-size: 24px;
}

/* 播放指示器样式 */
.playing-indicator {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(64, 158, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #409eff;
  box-sizing: border-box;
}

.equalizer {
  display: flex;
  align-items: end;
  height: 20px;
  gap: 2px;
}

.equalizer .bar {
  width: 3px;
  background-color: #409eff;
  border-radius: 1px;
  animation: equalizer 1.5s ease infinite alternate;
}

.equalizer .bar:nth-child(1) {
  height: 4px;
  animation-delay: 0s;
}

.equalizer .bar:nth-child(2) {
  height: 8px;
  animation-delay: 0.2s;
}

.equalizer .bar:nth-child(3) {
  height: 12px;
  animation-delay: 0.4s;
}

.equalizer .bar:nth-child(4) {
  height: 16px;
  animation-delay: 0.6s;
}

@keyframes equalizer {
  0% {
    height: 4px;
  }
  100% {
    height: 16px;
  }
}

.song-details {
  flex: 1;
  min-width: 0;
}

.song-name-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.song-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s ease;
}

.song-name.playing {
  color: #409eff;
  font-weight: 600;
}

.volume-icon {
  color: #409eff;
  font-size: 14px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

.song-artist {
  color: #666;
  font-size: 12px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.playing-duration {
  color: #409eff;
  font-weight: 500;
}

.like-btn {
  width: 32px;
  height: 32px;
}

.playing-btn {
  background: linear-gradient(45deg, #409eff, #67c23a);
  border-color: #409eff;
  color: white;
}

:deep(.song-table .el-table__row) {
  height: 80px;
  transition: all 0.3s ease;
  cursor: pointer;
}

:deep(.song-table .el-table__row:hover) {
  background-color: #f5f7fa;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 当前播放歌曲的行样式 */
:deep(.song-table .el-table__row.playing-row) {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  border-left: 4px solid #409eff;
}

:deep(.song-table .el-table__row.playing-row:hover) {
  background: linear-gradient(135deg, #e6f3ff 0%, #d9ecff 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

:deep(.song-table .el-table__cell) {
  padding: 8px 0;
  vertical-align: middle;
}

:deep(.song-table .el-table__cell .cell) {
  line-height: 1.4;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .library-view {
    padding: 16px;
    padding-bottom: 70px;
  }

  .song-info {
    gap: 8px;
  }

  .song-cover-container {
    width: 50px;
    height: 50px;
  }

  .song-name {
    font-size: 13px;
  }

  .song-artist {
    font-size: 11px;
  }

  .equalizer {
    height: 16px;
  }

  .equalizer .bar {
    width: 2px;
  }

  :deep(.song-table .el-table__row) {
    height: 70px;
  }
}

/* 响应式调整播放指示器 */
@media (max-width: 480px) {
  .playing-indicator {
    border-width: 1px;
  }

  .equalizer {
    height: 14px;
    gap: 1px;
  }

  .equalizer .bar {
    width: 1.5px;
  }
}
</style>